/**
 * String format
 * @memberOf {String} 
 * @return {String} 
 */
String.prototype.format = function() {
	var s = this, i = arguments.length;

	while (i--) {
		s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
	}
	return s;
};

/**
 * 替换.为\\.
 */
String.prototype.dot=function(){
	var s=this;
	s=s.replace(new RegExp('\\.','gm'),'\\\\.');
	return s;
}

/**
 * 字符串转bool类型,为“true”时返回true，不区分大小写，其他返回false。
 */
String.prototype.bool = function() {
    return (/^true$/i).test(this);
};

/**
 * 阻止事件向上冒泡
 * @param evt
 * @return
 */
function stopEventBubble(evt) {
	if (evt != null) {
		if (window.event) {
			evt.cancelBubble = true;
		} else {
			evt.stopPropagation();
		}
	}
}

/**
 * 封装jQuery的Ajax请求，让我们少写点代码
 * @param {Object} options:ajax请求的options,例如{url:'',data:postData,success:function(){}}
 */
function ajaxPost(options) {
	var realOptions = {
		type : "POST",
		timeout : 20000,
		cache : false,
		error : function(request, textStatus, errorThrown) {
			try{
				var result=eval('({0})'.format(request.responseText));
				if(result){
					showResult(result);
				}else{
					showError('请求发生错误！');
				}
			}catch(e){
				showError('请求发生错误！');
			}
		},
		async : false,
		dataType : "json",
		beforeSend:function(request){
			request.setRequestHeader('jQueryAjaxRequest','true');
		},
		success : function(data) {
			try {
				if (data.message && data.message != null && data.message != "") {
					alert(data.message);
				}
			} catch (e) {
			}
		}
	}
	$.extend(realOptions, options);

	$.ajax(realOptions);
}

/**
 * 显示结果
 * @param result {Object}，例如{state:1,message:'hello',otherInfo:{}}
 * @return void
 */
function showResult(result){
	if($('body').attr('class').indexOf('easyui-layout') <0){
		return;
	}
	
	hideResult();
	
	var template=''+
		'<span class="msg-icon {0}"></span>'+
		'{1}';
	var msg;
	if(result.state=="info"){
		msg=template.format('msg-icon-info',result.message);
	}
	if(result.state=="error"){
		msg=template.format('msg-icon-error',result.message);
	}
	if(result.state=="warning"){
		msg=template.format('msg-icon-warn',result.message);
	}
	if(result.state=="question"){
		msg=template.format('msg-icon-question',result.message);
	}
	var north=$('#msg').parent();
	var northH=north.outerHeight(true);
	$('#msg').html(msg).show();
	var msgH=$('#msg').outerHeight(true);
	north.panel('resize',{height:northH+msgH});
	$('body').layout('resize');
}

/**
 * 隐藏结果
 * @return void
 */
function hideResult(){
	if($('body').attr('class').indexOf('easyui-layout') <0){
		return;
	}
	
	if($('#msg').is(":visible")){
		var north=$('#msg').parent();
		var northH=north.outerHeight(true);
		var msgH=$('#msg').outerHeight(true);
		$('#msg').hide();
		var h=northH-msgH;
		if(h==0){
			h=1;
		}
		north.panel('resize',{height:h});
		$('body').layout('resize');
	}
}

/**
 * 用于在Jsp中显示警告
 * @param message 消息
 * @return void
 */
function showWarn(message){
	var result={state:'warning',message:message};
	showResult(result);
}

/**
 * 用于在Jsp中显示信息
 * @param message 消息
 * @return void
 */
function showInfo(message){
	var result={state:'info',message:message};
	showResult(result);
}

/**
 * 用于在Jsp中显示错误
 * @param message 消息
 * @return void
 */
function showError(message){
	var result={state:'error',message:message};
	showResult(result);
}

/**
 * 弹出窗口
 * 
 * @param {Object}
 *            option 选项（例如：{url:"http://www.baidu.com",height:600,width:800,scrollbars:'yes',maxWin:true}）
 */
function popWin(option) {
	if (!option) {
		alert("请设置option参数。");
	}
	if (!option.height) {
		option.height = 600;
	}
	if (!option.width) {
		option.width = 800;
	}
	// 获得窗口的垂直位置;
	var top = (window.screen.availHeight - option.height) / 2;
	// 获得窗口的水平位置;
	var left = (window.screen.availWidth - option.width) / 2;
	if(option.maxWin){
		option.height=window.screen.availHeight-50;
		option.width=window.screen.availWidth-25;
		top=0;
		left=0;
	}
	if (!option.scrollbars) {
		option.scrollbars = 'no';
	}

	
	var features='width={0},height={1},top={2},left={3},scrollbars={4},toolbar=no,menubar=no,resizable=yes,location=no,status=yes'
		.format(option.width,option.height,top,left,option.scrollbars);
	window.open(option.url,'',''+features);
}

/**
 * 得到DataGrid选中行的Id串
 * @param dataGridId DataGrid的Id。
 * @return Id串，以英文逗号分隔
 */
function getSelectedIds(dataGridId){
	var selectedRows = $('#'+dataGridId).datagrid("getSelections");
	var options=$('#'+dataGridId).datagrid("options");
	var idField=options.idField;
	var result = [];
	for(i=0; i < selectedRows.length; i++) {
		result.push(selectedRows[i][idField]);
	}
	return result.join(',');
}

/**
 * Json转String
 * @param o Json对象
 * @return 字符串
 */
function jsonToString(o) {
	var r = new Array();
	if (o == null || o == undefined) {
        return 'null';
    } 
	if (typeof o == "string")
		return "\""
				+ o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n")
						.replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
	if (typeof o == "object") {
		if (!o.sort) {
			for (var i in o)
				r.push(i + ":" + jsonToString(o[i]));
			if (!!document.all
					&& !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/
							.test(o.toString)) {
				r.push("toString:" + o.toString.toString());
			}
			r = "{" + r.join() + "}"
		} else {
			for (var i = 0; i < o.length; i++)
				r.push(jsonToString(o[i]));
			r = "[" + r.join() + "]"
		}
		return r;
	}
	return o.toString();
}

function includeString(array, str){
	var tstr = "." + array.join(".") + ".";
	return tstr.indexOf("." +str + ".") > -1;
}

/**
 * Json转String
 * @param o Json对象
 * @param includeProperties 要包含在字符串中的属性
 * @return 字符串
 */
function json2String(o, includeProperties) {
	var r = new Array();
	if (o == null || o == undefined) {
        return 'null';
    } 
	if (typeof o == "string")
		return "\""
				+ o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n")
						.replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
	if (typeof o == "object") {
		if (!o.sort) {
			for (var i in o){
				if(includeString(includeProperties, i)){
					r.push(i + ":" + json2String(o[i], includeProperties));
				}
			}
			r = "{" + r.join() + "}"
		} else {
			for (var i = 0; i < o.length; i++)
				r.push(json2String(o[i], includeProperties));
			r = "[" + r.join() + "]"
		}
		return r;
	}
	return o.toString();
}

/**
 * 验证开始日期是否大于结束日期
 */
function validateBetweenDate(startId,endId){
	var startTime=$("#"+startId).combo("getValue");
	var endTime=$("#"+endId).combo("getValue");
	if((startTime!=null ||startTime!="") && (endTime!=null || endTime!="")){
		startTime=new Date(startTime.replace(/-/g,"/"));
		endTime=new Date(endTime.replace(/-/g,"/"));
		if(startTime>endTime){
			showWarn("开始日期不能大于结束日期!");
			return false;
		}else{
			return true;
		}
	}
}

/**
 * 将表单域转化成Json对象
 * 用法：$("form").eq(0).serializeObject();
 * @memberOf {jQuery} form
 * @return {Object} Json对象
 */
$.fn.serializeObject = function() {
	var o = {};
	var a = this.serializeArray();
	$.each(a, function() {
				if (o[this.name]) {
					if (!o[this.name].push) {
						o[this.name] = [o[this.name]];
					}
					o[this.name].push(this.value || '');
				} else {
					o[this.name] = this.value || '';
				}
			});
	return o;
};

